$.fn.extend({
    region: function (options) {
        let regionInstance = new instance(this);
        regionInstance.init();

        let defaultOpt = {
            selected: []
        };

        return regionInstance;
    }
});

function appendOption(regions, dom) {
    $.each(regions, function (o, item) {
        dom.append($('<option value="' + item.id + '">' + item.name + '</option>'));
    });
}

let instance = function (obj) {
    this.dom = obj;
    this.regions = [];
    this.init = function (options) {
        let province = $('<select class="form-control input-sm" region-level="0"><option>请选择</option></select>');
        appendOption(region, province);

        this.dom.append(province);
        this.regions.push(region);
        let self = this;
        this.dom.on('change', 'select', function () {
            let $this = $(this);
            let regionLevel = parseInt($this.attr("region-level"));
            if (regionLevel < 3) {
                $this.nextAll().remove();
                let moveSize = self.regions.length - regionLevel - 1;
                for (let i = 0; i < moveSize; i++) {
                    self.regions.pop();
                }
                let selected;
                $.each(self.regions[self.regions.length - 1], function (o, item) {
                    if (item.id === parseInt($this.val())) {
                        selected = item;
                    }
                });
                if (selected.regions.length > 0) {
                    let regionSel = $('<select class="m-l-sm form-control input-sm" region-level="' + (regionLevel + 1) + '"><option>请选择</option></select>');
                    appendOption(selected.regions, regionSel);
                    self.dom.append(regionSel);
                    self.regions.push(selected.regions);
                }

            }
        })
    };
};